package org.blueoxygen.kukuruyuk.actions.supplier;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import org.apache.commons.beanutils.PropertyUtils;
import org.blueoxygen.cimande.LogInformation;
import org.blueoxygen.kukuruyuk.entity.Supplier;
public class SaveSupplier extends SupplierForm {
	
public String execute(){
		if(getSupplier().getName() == null ||
				"".equalsIgnoreCase(getSupplier().getName())){
				addActionError("Isikan nama supplier");
		}
		if(getSupplier().getAddress() == null ||
				"".equalsIgnoreCase(getSupplier().getAddress())){
				addActionError("Isikan alamat supplier");
		}
		if(getSupplier().getContactPerson() == null ||
				"".equalsIgnoreCase(getSupplier().getContactPerson())){
				addActionError("Isikan nama kontak");
		}
		if(getSupplier().getTelephone() == null ||
				"".equalsIgnoreCase(getSupplier().getTelephone())){
				addActionError("Isikan nomor telephon");
		}
		if(getSupplier().getAccountNumber() == null ||
				"".equalsIgnoreCase(getSupplier().getAccountNumber())){
			addActionError("isikan nomor akun");
     	}
		
		if(hasErrors()){
			 if(getSupplier().getId() != null &&
					 !"".equalsIgnoreCase(getSupplier().getId().trim())){
					 setSupplier((Supplier) manager.getById(Supplier.class, getSupplier().getId()));
					 }
			return INPUT;
		}

		LogInformation log;
		if(getSupplier().getId() == null || "".equalsIgnoreCase(getSupplier().getId())){
			log = new LogInformation();
			log.setCreateBy(sessionCredentials.getCurrentUser().getId());
			log.setCreateDate(new Timestamp(System.currentTimeMillis()));
			getSupplier().setId(null);
		} else {
			Supplier temp = getSupplier();
			setSupplier((Supplier) manager.getById(Supplier.class, getSupplier().getId()));
			log = getSupplier().getLogInformation();
			try {
				PropertyUtils.copyProperties(getSupplier(), temp);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		
		
		log.setLastUpdateBy(sessionCredentials.getCurrentUser().getId());
		log.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
		log.setActiveFlag(1);
		
		
		getSupplier().setLogInformation(log);
		manager.save(getSupplier());
		return SUCCESS;
	}

	
}	
